package project.euler.honk.problem.to50;

final class Problem32 {

	private static final boolean[] addMe = new boolean[8000];

	private static int digits(int number) {
		if (number < 10)
			return 1;
		if (number < 100)
			return 2;
		if (number < 1000)
			return 3;
		if (number < 10000)
			return 4;
		if (number < 100000)
			return 5;
		if (number < 1000000)
			return 6;
		if (number < 10000000)
			return 7;
		if (number < 100000000)
			return 8;
		if (number < 1000000000)
			return 9;
		return 99;
	}

	private static boolean subCheck(int x, boolean[] bla) {
		final int x_d = digits(x);
		for (int i = 0; i < x_d; i++) {
			int c = x % 10;
			if (c == 0)
				return false;
			if (bla[c - 1])
				return false;
			bla[c - 1] = true;
			x /= 10;
		}
		return true;
	}

	private static boolean check(int x, int y, int prod) {

		final boolean[] bla = new boolean[9];
		if (!subCheck(x, bla))
			return false;
		if (!subCheck(y, bla))
			return false;
		if (!subCheck(prod, bla))
			return false;
		return true;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		int sum = 0;
		for (int i = 0; i < 10000; i++) {
			for (int j = 1; true; j++) {
				final int prod = i * j;
				int numDigits = digits(i) + digits(j) + digits(prod);
				if (numDigits < 9)
					continue;
				if (numDigits > 9)
					break;
				if (check(i, j, prod)) {
					if (!addMe[prod])
						sum += prod;
					else
						addMe[prod] = true;
				}
			}
		}

		long end = System.currentTimeMillis();
		System.out.println("Result: " + sum + " Time: " + (end - start));
	}

}
